<?php

namespace MoChat\App\Statistic\Action\Client;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 客户统计折线图
 * @Controller
 */
class ClientBroken extends AbstractAction
{

    private function generationTime($list): array
    {
        if (empty($list)) {
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-01', strtotime('+1 month'));
        } else {
            $startDate = reset($list)->times;
            $endDate = end($list)->times;
        }
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $timeRage = [];
        while (true) {
            if ($startTime > $endTime) {
                break;
            }
            $date = date('Y-m-d', $startTime);
            $timeRage[] = $date;
            $startTime += 86400;
        }
        return $timeRage;
    }

    private function formatData($list): array
    {
        $timeRage = $this->generationTime($list);
        $value = [];
        $list = !empty($list) ? array_column($list, null, 'times') : [];
        foreach ($timeRage as $time) {
            $value[] = $list[$time]->count ?? 0;
        }
        return [
            'brokenKey' => $timeRage,
            'brokenValue' => $value,
        ];
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticClient/clientBroken", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $data['startTime'] = $data['startTime'] ?? date('Y-m-01 00:00:00');
        $data['endTime'] = $data['endTime'] ?? date('Y-m-d H:i:s');
        if ($data['type'] == 1) {
            $list = Db::table('client')
                ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                    $query->whereBetween('created_at', [$data['startTime'], $data['endTime']]);
                })
                ->when(!empty($data['employeeId']), function ($query) use ($data) {
                    $query->where('work_employee_id', $data['employeeId']);
                })->select([
                    Db::raw("DATE_FORMAT(`created_at`, '%Y-%m-%d') AS `times`"),
                    Db::raw('COUNT(*) as count'),
                ])->groupBy([
                    Db::raw("DATE_FORMAT(`created_at`, '%Y-%m-%d')")
                ])->orderBy('created_at', 'asc')->get();
        } else {
            $list = Db::table('client')
                ->join('client_follow_record as record','record.client_id','=','client.id')
                ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                    $query->whereBetween('record.created_at', [$data['startTime'], $data['endTime']]);
                })
                ->when(!empty($data['employeeId']), function ($query) use ($data) {
                    $query->where('client.work_employee_id', $data['employeeId']);
                })->select([
                    Db::raw("DATE_FORMAT(mc_record.`created_at`, '%Y-%m-%d') AS `times`"),
                    Db::raw('COUNT(*) as count'),
                ])->groupBy([
                    Db::raw("DATE_FORMAT(mc_record.`created_at`, '%Y-%m-%d')"),
                    'record.client_id',
                ])->orderBy('record.created_at', 'asc')->get();
        }
        $list || $list = collect([]);
        $list = $list->toArray();
        return $this->formatData($list);
    }
}
